import axios from './axios'
import { API_DEFAULT_CONFIG, BASE_API_URL } from '@config'
import API_CONFIG from '@service/apis'


class MakeApi {
	constructor( options ) {
		this.api = {};
		this.apiBuilder( options )
	}

	apiBuilder( {
		            sep = '|',
		            config = {},
		            mock = false,
		            debug = false,
		            mockBaseURL = ''
	            } ) {
		Object.keys( config ).map( namespace => {
			this._apiSingleBuilder( {
				namespace,
				mock,
				mockBaseURL,
				sep,
				debug,
				config: config[ namespace ]
			} )
		} )
	}
	
	 _apiSingleBuilder( {
		                   namespace,
		                   sep = '|',
		                   config = {},
		                   mock = false,
		                   debug = false,
		                   mockBaseURL = ''
	                   } ) {
		this.api[ namespace ] = {};
		Object.keys( config ).map( key => {
			const { method, desc, path, mockPath, mockEnable, debug, params } = config[ key ];
			const isMock = process.env.NODE_ENV === 'production' ? false : mock || mockEnable;
			const url = isMock ? mockPath : path;
			const baseURL = isMock ? mockBaseURL: BASE_API_URL;

			// debug && assert( url.indexOf( '/' ) === 0, `${url} :接口路径path，首字符应为/` );

			Object.defineProperty( this.api[ namespace ], `${key}`, {
				 value( outerParams, outerOptions ) {
					const _data = _.isEmpty( outerParams ) ? params : _.pick( _.assign( {}, params, outerParams ), Object.keys( params ) );
					const _options = isMock?{ url, desc, baseURL, method }:{ url, desc, method };
					
					return axios( _normoalize( _.assign( _options, outerOptions ), _data ) )
				}
			} )
		} )
	}
}

function _normoalize( options, data ) {
	if ( options.method === 'POST' ) {
		options.data = data
	} else if ( options.method === 'GET' ) {
		options.params = data
	}
	return options
}


export default new MakeApi( {
	config: API_CONFIG,
	...API_DEFAULT_CONFIG
} )[ 'api' ]

